package hyo.hun.lifemanager.connect;

import java.io.IOException;
import java.util.List;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;

import com.google.api.client.extensions.android2.AndroidHttp;
import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.googleapis.services.GoogleKeyInitializer;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.common.collect.Lists;



public class CalendarConnect {

	private static final String KEY = "AIzaSyA_idVqUz3ZroVw9O7ZNIGKR6mAVFdMFGc";
	
	private Context context;
	private Activity activity;
	
	
	private static final String AUTH_TOKEN_TYPE = "cl";
	private static final String PREF_ACCOUNT_NAME = "accountName";
	private static final String PREF_AUTH_TOKEN = "authToken";
	
	public static final int REQUEST_AUTHENTICATE = 0;
	
	private final HttpTransport transport = AndroidHttp.newCompatibleTransport();
	private final JsonFactory jsonFactory = new GsonFactory();
	
	private SharedPreferences settings;
	private String accountName;
	private String authToken;
	
	private GoogleAccountManager accountManager;
	
	private static com.google.api.services.calendar.Calendar client;
	
	private List<CalendarInfo> listCalendars = Lists.newArrayList();
	private List<EventInfo> listEvents = Lists.newArrayList();
	
	private int calendarId = -1;
	
	
	
	
	
	
	
	private CalendarConnect(){};
	
//	public CalendarConnect(Context context, Activity activity)
//	{
//		this.context = context;
//		this.activity = activity;
//	}
	
	private static CalendarConnect calendarConnect = new CalendarConnect();
	public static CalendarConnect getCalendarConnect()
	{
		return calendarConnect;
	}
	
	public static com.google.api.services.calendar.Calendar getClient()
	{
		// 연결 및 계정 체크 필요함.
		return client;
	}
	
	public void startConnect(Context context, Activity activity)
	{
		this.context = context;
		this.activity = activity;
		HttpRequestInitializer requestInitializer = new HttpRequestInitializer() 
		{
			public void initialize(HttpRequest request) throws IOException 
			{
				request.getHeaders().setAuthorization(GoogleHeaders.getGoogleLoginValue(authToken));
			}
		};
		client = new com.google.api.services.calendar.Calendar.Builder(transport, jsonFactory, requestInitializer)
				.setApplicationName("LifeManger")
	            .setJsonHttpRequestInitializer(new GoogleKeyInitializer(KEY)).build();
		settings = context.getSharedPreferences("pref", Activity.MODE_PRIVATE);
		accountName = settings.getString(PREF_ACCOUNT_NAME, null);
	    authToken = settings.getString(PREF_AUTH_TOKEN, null);
	    //Logger.getLogger("com.google.api.client").setLevel(LOGGING_LEVEL);
	    accountManager = new GoogleAccountManager(context);
	    //registerForContextMenu(getListView());
	    gotAccount();
	}
	
	private void gotAccount() 
	{
		Account account = accountManager.getAccountByName(accountName);
		if (account == null) 
		{
			chooseAccount();
			return;
		}
		if (authToken != null) 
		{
			onAuthToken();
			return;
		}
		accountManager.getAccountManager().getAuthToken(account, AUTH_TOKEN_TYPE, true,
        new AccountManagerCallback<Bundle>() 
        {
			public void run(AccountManagerFuture<Bundle> future) 
			{
				try 
				{
					Bundle bundle = future.getResult();
					if (bundle.containsKey(AccountManager.KEY_INTENT)) 
					{
						Intent intent = bundle.getParcelable(AccountManager.KEY_INTENT);
						intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_NEW_TASK);
						activity.startActivityForResult(intent, REQUEST_AUTHENTICATE);
					} else if (bundle.containsKey(AccountManager.KEY_AUTHTOKEN)) 
					{
						setAuthToken(bundle.getString(AccountManager.KEY_AUTHTOKEN));
						onAuthToken();
					}
				} catch (Exception e) 
				{
					//Log.e(TAG, e.getMessage(), e);
				}
            }
        }, null);
	}

	private void chooseAccount() 
	{
		accountManager.getAccountManager().getAuthTokenByFeatures(GoogleAccountManager.ACCOUNT_TYPE,
        AUTH_TOKEN_TYPE, null, activity, null, null,
        new AccountManagerCallback<Bundle>() 
        {
			public void run(AccountManagerFuture<Bundle> future) 
			{
				Bundle bundle;
				try 
				{
					bundle = future.getResult();
					setAccountName(bundle.getString(AccountManager.KEY_ACCOUNT_NAME));
					setAuthToken(bundle.getString(AccountManager.KEY_AUTHTOKEN));
					//onAuthToken();
				} catch (OperationCanceledException e) {
					// user canceled
				} catch (AuthenticatorException e) {
					//Log.e(TAG, e.getMessage(), e);
				} catch (IOException e) {
					//Log.e(TAG, e.getMessage(), e);
				}
			}
        }, null);
	}
	
	private void setAccountName(String accountName) 
	{
		SharedPreferences.Editor editor = settings.edit();
	    editor.putString(PREF_ACCOUNT_NAME, accountName);
	    editor.commit();
	    this.accountName = accountName;
	}
	
	private void setAuthToken(String authToken) 
	{
	    SharedPreferences.Editor editor = settings.edit();
	    editor.putString(PREF_AUTH_TOKEN, authToken);
	    editor.commit();
	    this.authToken = authToken;
	}
	
	public List<CalendarInfo> getCalendarList()
	{
		return listCalendars;
	}
	
	public void setCalendarList(List<CalendarInfo> list)
	{
		listCalendars = list;
	}
	
	public List<EventInfo> getEventList()
	{
		return listEvents;
	}
	
	public void setEventList(List<EventInfo> list)
	{
		listEvents = list;
		
		for (int i=0; i<listEvents.size(); i++)
		{
			Log.e("events", listEvents.get(i).toString());
		}
	}
	
	public void loadEvents(String calendarId, Context context)
	{
		new AsyncLoadEventArange(this, context, calendarId).execute();
	}
	
	void onAuthToken() 
	{
	    new AsyncLoadCalendars(this, context).execute();
	}
	
	
}
